import { RouteRecordRaw } from 'vue-router';
import defaultSettings from '@g/settings';
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import getRouteByRole from './utils/getRouteByRole';
import getRouteByRouteId from './utils/getRouteByRouteId';
import constantRoutes from '@/router/modules/constantRoutes';

export const usePermissionStore = defineStore('permission', {
  state: () => {
    return {
      isGetUserInfo: false, // get userInfo
      routes: [] as RouteRecordRaw[], //将过滤后的异步路由和静态路由集合
      addRoutes: [] as RouteRecordRaw[] //过滤后的异步路由
    }
  },

  actions: {
    // 解析出显示的路由菜单列表
    generateRoutes() {
      return new Promise(resolve => {
        const userInfo = useUserStore().userInfo
        const permissionType = defaultSettings.permissionType
        // 获取路由列表
        let routes: RouteRecordRaw[] = []
        if (permissionType === 'routeId') routes = (userInfo && userInfo[defaultSettings.permissionListKey]) ? getRouteByRouteId(userInfo[defaultSettings.permissionListKey]) as RouteRecordRaw[] : []
        else if (permissionType === 'role') routes = (userInfo && userInfo.roles) ? getRouteByRole(userInfo?.roles) as RouteRecordRaw[] : []
  
        this.$patch(state => {
          state.addRoutes = routes
          state.routes = constantRoutes.concat(routes)
        })
  
        resolve(routes)
      })
    }
  }
})
